<template>
  <div class="home">
    <!-- 一定要指定row-key 属性！，否则拖拽排序会出问题  -->
    <el-table :data="tableData" row-key="id">
      <el-table-column prop="id" label="ID"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
    </el-table>
  </div>
</template>

<script>
// draggable 依赖于 Sortable，当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable";
import Sortable from "sortablejs";

export default {
  name: "Home",
  data() {
    return {
      tableData: [
        {
          name: "这是line1",
          id: 1,
        },
        {
          name: "这是line2",
          id: 2,
        },
        {
          name: "这是line3",
          id: 3,
        },
        {
          name: "这是line4",
          id: 4,
        },
      ],
    };
  },
  created() {
    this.$nextTick(() => {
      this.drag();
    });
  },
  methods: {
    myend() {
      console.log(this.tableData);
    },
    drag() {
      const el = document.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      Sortable.create(el, {
        disabled: false, // 拖拽不可用? false 启用
        ghostClass: 'sortable-ghost', //拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        onEnd: (e) => { // 拖拽结束时的触发
            let arr = this.tableData; // 获取表数据
            arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理，获取最新的表格数据
            this.$nextTick(function () {
              this.tableData= arr;
              console.log(this.tableData)
            })
        },
      });
    },
  },
  components: {
    draggable,Sortable
  },
};
</script>
